/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rbh.risk.service.impl;

import com.rbh.risk.dao.OpduserDao;
import com.rbh.risk.entity.Opduser;
import com.rbh.risk.entity.Profile;
import com.rbh.risk.service.ProfileService;
import com.rbh.risk.support.ProfileUserDetails;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.NoResultException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/*
 * Spring-security requires an implementation of UserDetailService. 
 */
@Service(value = "userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService, Serializable {

    @Autowired
    private OpduserDao opduserDao;
    @Autowired
    private ProfileService profileService;

    @Transactional(readOnly = false)
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ProfileUserDetails profileUserDetails = null;
        try {
            Opduser opduser = null;
            Profile profile = null;

            opduser = this.opduserDao.getByUsername(username);
            if (opduser != null) {
                profile = this.profileService.getByOpduser(opduser);

                String authoritie = "ROLE_REGISTERED";

                if (profile.getRole().getRoleName().equalsIgnoreCase("Administrator")
                        || profile.getRole().getRoleName().equalsIgnoreCase("Root")) {
                    authoritie = "ROLE_ADMIN";
                }

                Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                grantedAuthorities.add(new GrantedAuthorityImpl(authoritie));

                profileUserDetails = new ProfileUserDetails(opduser.getLoginname(), opduser.getPassweb(), profile, grantedAuthorities);
            }
            return profileUserDetails;
        } catch (NoResultException e) {
            throw new UsernameNotFoundException("No such user");
        }
    }
}